import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { ReactHTMLElement, Component } from 'react'


interface User {  
// 用户的数据定义
  name: string
  age: number
  country: string
}

function searchByAge(users: Array<User>, age: number): Array<User> {
  if (isNaN(age)) {
    return users
  }
  var result: Array<User> = [] 
  for (var user of users) {
    if (user.age === age) {
      result.push(user)
    }
  }
  return result
}

function searchByName(users: Array<User>, name: string): Array<User> {
  if (name === '') {
    return users
  }
  var result: Array<User> = []
  for (var user of users) {
    if (user.name === name) {
      result.push(user)
    }
  }
  return result
}

interface TableProps {
// Table 使用的属性值
  users: Array<User>
}

class Table extends Component<TableProps, null> {
// 列表元素
  constructor(props: TableProps) {
    super(props)
  }

  public render() {
  // 渲染 hook 函数
    var rows = []
    for (var [i, user] of this.props.users.entries()) {
      rows.push(
        // JSX 元素
        <tr key={i}>
          <td>{user.name}</td>
          <td>{user.age}</td>
          <td>{user.country}</td>
        </tr>
      )
    }
    return (
      // JSX 元素
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Country</th>
          </tr>
        </thead>
        <tbody>
          {rows}
        </tbody>
      </table>
    )  
  }
}

interface UserPanelProps {
// 菜单元素使用的属性值
  users: Array<User>
}

interface UserPanelState {
  users: Array<User>
}

class UserPanel extends Component<UserPanelProps, UserPanelState> {
// 菜单元素
  constructor(props: UserPanelProps) {
    super(props)
    this.state = {
      users: props.users
    }
  }

  public render() {
  // 渲染 hook 函数
    return (
      // JSX 元素
      <div>
        <h1>User Table</h1>

        <input type="text" placeholder="enter age filter ..."
               onChange={(e: any) => this.changeAge(e.target.value)} />
               
        <input type="text" placeholder="enter name filter ..."
               onChange={(e: any) => this.changeName(e.target.value)} />

        <Table users={this.state.users} />
      </div>
    )
  }

  private changeAge(value: string) {
    this.setState({
      users: searchByAge(this.props.users, parseInt(value))
    })
  }

  private changeName(value: string) {
    this.setState({
      users: searchByName(this.props.users, value)
    })
  }
}

function main() {
  window.addEventListener('load', () => {
    var users = [
      {
        name: 'XiaoMing', age: 21, country: 'CHN'
      },
      {
        name: 'Tom', age: 21, country: 'USA'
      },
      {
        name: 'Lili', age: 16, country: 'EN'
      },
    ]
    // 开始渲染 （指定元素 -> 装载数据 -> 渲染）
    // ReactDOM.render(JSX.Element, HTMLElement)
    ReactDOM.render(<UserPanel users={users} />, 
                    document.getElementById('wrapper'))
  })
}

main()

